package com.woniuxy.project115.kaer.gateway.filter;

import com.woniuxy.project115.kaer.commons.util.JwtUtil;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.annotation.Order;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.net.URI;
import java.util.List;

@Component
@Order(1)
@ConfigurationProperties(prefix = "gateway.filter")
@Data
public class LoginFilter implements GlobalFilter {
    private List<String> whiteRequestList;
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

        ServerHttpRequest request = exchange.getRequest();//获取请求对象
        ServerHttpResponse response = exchange.getResponse();//获取响应对象

        URI uri = request.getURI();
        String path = uri.getPath();//去掉端口和ip之后
        System.out.println(path);
        if (path.contains("swagger")||path.contains("api-docs")||whiteRequestList.contains(path)){
            return chain.filter(exchange);
        } else {
            //判断token
            List<String> token = request.getHeaders().get("token");
            if (token==null || token.isEmpty()){
                throw new RuntimeException("未登录");
            }
            //判断token的合法性
            try {
                JwtUtil.parseToken(token.get(0));
            } catch (Exception e) {
                throw new RuntimeException("令牌无效");
            }
        }
        return chain.filter(exchange);
    }
}
